package org.seven.jrdp.biz.t.service;

import java.util.List;
import java.util.Map;

import org.seven.jrdp.biz.t.mapper.THtMapper;
import org.seven.jrdp.biz.t.model.THt;
import org.seven.jrdp.commons.exception.BizException;
import org.seven.jrdp.commons.model.Option;
import org.seven.jrdp.commons.mybatis.model.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class THtService {
	@Autowired
	private THtMapper tHtMapper;

	@Transactional(readOnly = true)
	public PageInfo<THt> find(Map<String, Object> map, PageRequest pageRequest) {
		PageHelper.startPage(pageRequest.getPage(), pageRequest.getRows());
		return new PageInfo<THt>(tHtMapper.find(map));
	}

	@Transactional(readOnly = true)
	public THt get(String id) {
		return tHtMapper.selectByPrimaryKey(id);
	}

	@Transactional
	public void insert(THt tHt) {
		tHt.setYckzl(0);
		tHtMapper.insertSelective(tHt);
	}

	@Transactional
	public void update(THt tHt) {
		Integer yckzl = getYckzl(tHt.getId());
		if (yckzl == null) {
			throw new BizException("未查询到已出库重量");
		}
		if (tHt.getHtzl() < yckzl) {
			throw new BizException("合同重量不允许少于已出库重量");
		}
		tHtMapper.updateByPrimaryKeySelective(tHt);
	}

	@Transactional
	public void delete(String id) {
		THt tHt = get(id);
		if (tHt.getYckzl() > 0) {
			throw new BizException("合同已关联出库单，不允许删除");
		}
		tHt.setDeleteFlag("1");
		tHtMapper.updateByPrimaryKeySelective(tHt);
	}

	@Transactional(readOnly = true)
	public List<Option> getOption() {
		return tHtMapper.getOption();
	}

	@Transactional
	public Integer getYckzl(String id) {
		return tHtMapper.getYckzl(id);
	}

	@Transactional
	public void add(String id, int zl) {
		THt tHt = get(id);
		tHt.setYckzl(tHt.getYckzl() + zl);
		tHtMapper.updateByPrimaryKeySelective(tHt);
	}

	@Transactional
	public void subtract(String id, int zl) {
		THt tHt = get(id);
		tHt.setYckzl(tHt.getYckzl() - zl);
		tHtMapper.updateByPrimaryKeySelective(tHt);
	}
}